<template>
  <div v-if="chartData" class="container">
    <data-chart
      id="EvmVsTime"
      :data="chartData"
      title="误差向量幅度 vs 时间"
      :config="config"
    />
  </div>
</template>

<script setup>
  // EVM vs Time 图表
  import { queryEvm } from '@/api/charts'
  import DataChart from '@/components/DataChart'
  import useChartsStore from '@/store/modules/charts'
  import useDmFormStore from '@/store/modules/form/dmForm'
  import Interval from '@/common/classes/interval'
  import useChartOptions from '@/common/hooks/chartOptions'
  import { cloneDeep } from 'lodash'

  defineComponent([DataChart])
  const props = defineProps({
    params: {
      type: Object,
      default: () => ({})
    }
  })
  const chartsStore = useChartsStore()
  const chartData = ref(null)
  const { resultLen } = useDmFormStore()
  const { chartOptions } = useChartOptions()
  const isStatic = chartsStore.static.enabled
  let interval = null

  const genearteChartsOptions = (chartOptions) => {
    const currentOptions = cloneDeep(chartOptions)
    currentOptions.yAxis.min = 0
    currentOptions.yAxis.max = undefined
    currentOptions.xAxis.min = 0
    currentOptions.xAxis.labels.formatter = function() {
      if (this.value === 0 || this.value === resultLen - 1) {
        return this.value
      }
      return ''
    }
    currentOptions.xAxis.labels.renderFormatter = function() {
      return this.value
    } 
    currentOptions.xAxis.max = resultLen - 1
    currentOptions.xAxis.tickInterval = (resultLen - 1) / 10
    currentOptions.yAxis.tickAmount = 11
    currentOptions.yAxis.unit = '%'
    return currentOptions
  }
  const config = reactive({
    type: 'static', // 动态图: trend 静态:static
    chart: computed(() => genearteChartsOptions(chartOptions.value)),
    viewNum: resultLen,
    start: 0
  })

  const renderView = () => {
    if (isStatic) {
      config.viewNum = 'all'
      return
    }
    const { settings } = chartsStore
    nextTick(() => {
      interval = Interval.create(
        (start) => {
          config.start = start
        },
        resultLen,
        resultLen,
        chartData.value.length
      )
    })
  }
  const init = async () => {
    const body = chartsStore.getFileInfo()
    const { data } = await queryEvm(body)
    chartData.value = data.demoDataVector
    renderView()
  }

  onMounted(() => {
    init()
  })
  onUnmounted(() => {
    if (interval && !interval.destroyed) {
      interval.destroy()
    }
  })
</script>
